package com.newviews.tcmip.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newviews.tcmip.common.constant.CommonConsts;
import com.newviews.tcmip.common.enums.UiElCodeEnums;
import com.newviews.tcmip.common.model.PageModel;
import com.newviews.tcmip.common.model.ResultModel;
import com.newviews.tcmip.common.utils.StringUtils;
import com.newviews.tcmip.pojo.po.*;
import com.newviews.tcmip.dao.EtcmPxHerbMapper;
import com.newviews.tcmip.service.inf.EtcmHerbExServiceInf;
import com.newviews.tcmip.service.inf.EtcmPxHerbServiceInf;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.newviews.tcmip.web.vo.etcmpx.PxHerbStatisticsRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;


import java.io.FileNotFoundException;
import java.io.PrintStream;
/**
 * <p>
 * 处方-中草药关系表 服务实现类
 * </p>
 *
 * @author lxc
 * @since 2024-03-01
 */
@Service
public class EtcmPxHerbServiceImpl extends ServiceImpl<EtcmPxHerbMapper, EtcmPxHerbPo> implements EtcmPxHerbServiceInf {
    @Autowired
    private EtcmHerbExServiceInf etcmHerbExService;
    @Autowired
    private EtcmPxHerbMapper etcmPxHerbMapper;

    @Override
    public ResultModel<PageModel<Map<String, String>>> getInfo(String prescriptionId,String content,String herbMeridians,String herbProperty,String herbFlavor, String sortType,String uiTypeCode, String langCode, Integer pageNo, Integer pageSize) {
        uiTypeCode = CommonConsts.UI_HERB;
        if (org.apache.commons.lang3.StringUtils.isBlank(herbFlavor) && org.apache.commons.lang3.StringUtils.isBlank(herbProperty) && org.apache.commons.lang3.StringUtils.isBlank(herbMeridians)){
            return new ResultModel<PageModel<Map<String,String>>>().success(new PageModel<>());
        }
        QueryWrapper<EtcmPxHerbPo> queryWrapper=new QueryWrapper<>();
//        queryWrapper.eq("t1.px_id", prescriptionId);
//        queryWrapper.eq("t3.px_code", prescriptionId);
        if(StringUtils.isNotBlank(content)){
            queryWrapper.and(w->w.like( "t2.herb_zh_name", content)
                    .or().like( "t2.herb_zh_name_py", content)
                    .or().like( "t2.herb_zh_name_wb", content)
                    .or().like( "t2.herb_zh_name_abb", content)
                    .or().like( "t2.herb_en_name", content)
                    .or().like( "t2.herb_en_name_abb", content)
                    .or().like( "t2.herb_latin_name", content)
                    .or().like( "t2.herb_latin_name_abb", content)
                    .or().like( "t2.herb_name_alias", content)
            );
        }


        if(StringUtils.isNotBlank(herbMeridians)){
            queryWrapper.in("t6.meridians_code",herbMeridians.split(CommonConsts.SPIT));
        }
        if(StringUtils.isNotBlank(herbProperty)){
            queryWrapper.in("t5.property_code",herbProperty.split(CommonConsts.SPIT));
        }
        if(StringUtils.isNotBlank(herbFlavor)){
            queryWrapper.in("t4.flavor_code",herbFlavor.split(CommonConsts.SPIT));
        }

        if(sortType.equals(CommonConsts.SORT_TYPE_ASC)){
            queryWrapper.orderByAsc("t1.herb_id");
        }else {
            queryWrapper.orderByDesc("t1.herb_id");
        }
        queryWrapper.groupBy("t1.herb_id");
        IPage<EtcmPxHerbPo> iPage = etcmPxHerbMapper.getPage(new Page<>(pageNo, pageSize), queryWrapper,prescriptionId);
        List<Map<String,String>> list=new ArrayList<>();
        for(EtcmPxHerbPo etcmPxHerbPo:iPage.getRecords()){
            List<EtcmHerbExPo> herbExPoList = etcmHerbExService.list(new QueryWrapper<EtcmHerbExPo>().eq("herb_id", etcmPxHerbPo.getHerbId()).eq("ui_type_code", uiTypeCode).eq("language_code", langCode));
            Map<String,String> map=new HashMap<>(16);
            map.put(UiElCodeEnums.QUANTITY.getUiElCode(), etcmPxHerbPo.getQuantity());
            for(EtcmHerbExPo etcmHerbExPo:herbExPoList){
                map.put(etcmHerbExPo.getUiElCode(), etcmHerbExPo.getHerbExCon());
            }
            list.add(map);
        }
        PageModel<Map<String,String>> page=new PageModel<>();
        page.setPageNo(pageNo);
        page.setPageSize(pageSize);
        page.setRecords(list);
        page.setTotalCount(iPage.getTotal());
        return new ResultModel<PageModel<Map<String,String>>>().success(page);
    }
    @Override
    public List<Map<String, String>> getPxHerbDownload(String pxId, String herbFlavor, String herbProperty, String herbMeridians, String content, String langCode, String uiTypeCode, String sortType) {
        uiTypeCode = CommonConsts.UI_HERB;
        if (org.apache.commons.lang3.StringUtils.isBlank(herbFlavor) && org.apache.commons.lang3.StringUtils.isBlank(herbProperty) && org.apache.commons.lang3.StringUtils.isBlank(herbMeridians)){
            return new ArrayList<>();
        }
        QueryWrapper<EtcmPxHerbPo> queryWrapper=new QueryWrapper<>();
        //queryWrapper.eq("t1.px_id", pxId);
        if(StringUtils.isNotBlank(content)){
            queryWrapper.and(w->w.like( "t2.herb_zh_name", content)
                    .or().like( "t2.herb_zh_name_py", content)
                    .or().like( "t2.herb_zh_name_wb", content)
                    .or().like( "t2.herb_zh_name_abb", content)
                    .or().like( "t2.herb_en_name", content)
                    .or().like( "t2.herb_en_name_abb", content)
                    .or().like( "t2.herb_latin_name", content)
                    .or().like( "t2.herb_latin_name_abb", content)
                    .or().like( "t2.herb_name_alias", content)
            );
        }
        if(StringUtils.isNotBlank(herbMeridians)){
            queryWrapper.in("t6.meridians_code",herbMeridians.split(CommonConsts.SPIT));
        }
        if(StringUtils.isNotBlank(herbProperty)){
            queryWrapper.in("t5.property_code",herbProperty.split(CommonConsts.SPIT));
        }
        if(StringUtils.isNotBlank(herbFlavor)){
            queryWrapper.in("t4.flavor_code",herbFlavor.split(CommonConsts.SPIT));
        }
        if(StringUtils.isNotBlank(sortType) && sortType.equals(CommonConsts.SORT_TYPE_ASC)){
            queryWrapper.orderByAsc("t1.herb_id");
        }else {
            queryWrapper.orderByDesc("t1.herb_id");
        }
        queryWrapper.groupBy("t1.herb_id");
        List<EtcmPxHerbPo> iPage = this.baseMapper.getPxHerbDownload( queryWrapper,pxId);
        List<Map<String,String>> list=new ArrayList<>();
        for(EtcmPxHerbPo etcmPxHerbPo:iPage){
            List<EtcmHerbExPo> herbExPoList = etcmHerbExService.list(new QueryWrapper<EtcmHerbExPo>().eq("herb_id", etcmPxHerbPo.getHerbId()).eq("ui_type_code", uiTypeCode).eq("language_code", langCode));
            Map<String,String> map=new HashMap<>(16);
            map.put(UiElCodeEnums.QUANTITY.getUiElCode(), etcmPxHerbPo.getQuantity());
            for(EtcmHerbExPo etcmHerbExPo:herbExPoList){
                map.put(etcmHerbExPo.getUiElCode(), etcmHerbExPo.getHerbExCon());
            }
            list.add(map);
        }

        return list;
    }
//    @Override
//    public List<Map<String, String>> getPxHerbList(String prescriptionId, String content, String herbType, String herbProperty, String herbFlavor, String uiTypeCode, String langCode) {
//        QueryWrapper<EtcmPxHerbPo> queryWrapper=new QueryWrapper<>();
//        queryWrapper.eq("t1.px_id", prescriptionId);
//        if(StringUtils.isNotBlank(content)){
//            queryWrapper.and(w->w.like("t2.herb_zh_name", content)
//                    .or().like("t2.herb_en_name", content)
//                    .or().like("t2.herb_latin_name", content));
//        }
//        if(StringUtils.isNotBlank(herbType)){
//            queryWrapper.in("t2.herb_species_code",herbType.split(CommonConsts.SPIT));
//        }
//        if(StringUtils.isNotBlank(herbProperty)){
//            queryWrapper.in("t2.herb_property_code",herbProperty.split(CommonConsts.SPIT));
//        }
//        if(StringUtils.isNotBlank(herbFlavor)){
//            queryWrapper.in("t2.herb_flavor_code",herbFlavor.split(CommonConsts.SPIT));
//        }
//        List<EtcmPxHerbPo> resultList = this.baseMapper.getList(queryWrapper);
//        List<Map<String,String>> list=new ArrayList<>();
//        for(EtcmPxHerbPo etcmPxHerbPo:resultList){
//            List<EtcmHerbExPo> herbExPoList = etcmPxHerbMapper.getHerbList(new QueryWrapper<EtcmHerbExPo>().eq("herb_id", etcmPxHerbPo.getHerbId()).eq("ui_type_code", uiTypeCode).eq("language_code", langCode));
//            Map<String,String> map=new HashMap<>(16);
//            map.put(UiElCodeEnums.QUANTITY.getUiElCode(), etcmPxHerbPo.getQuantity());
//            for(EtcmHerbExPo etcmHerbExPo:herbExPoList){
//                map.put(etcmHerbExPo.getUiElName(), etcmHerbExPo.getHerbExCon());
//            }
//            list.add(map);
//        }
//        return list;
//    }

    @Override
    public List<Map<String, String>> getIngredientList(String metabolicStability, String TransportMode, String halfLifePeriod, String content, String langCode, String uiTypeCode, String prescriptionId) {
        List<EtcmPxHerbPo> list = this.list(new QueryWrapper<EtcmPxHerbPo>().eq(EtcmPxHerbPo.PX_ID, prescriptionId).eq(EtcmPxHerbPo.STATUS, CommonConsts.COMMON_YES));
        List<String> herbList=list.stream().map(EtcmPxHerbPo::getHerbId).collect(Collectors.toList());
        QueryWrapper<EtcmHerbIngrPo> wrapper=new QueryWrapper<>();
        if(StringUtils.isNotBlank(metabolicStability)){
            String[] msArray = metabolicStability.split(CommonConsts.SPIT);
            wrapper.in("t2.ingr_metabolic_stability_code", Arrays.asList(msArray));
        }
        if(StringUtils.isNotBlank(TransportMode)){
            String[] tmArray = TransportMode.split(CommonConsts.SPIT);
            wrapper.in("t2.ingr_transport_mode_code", Arrays.asList(tmArray));
        }
        if(StringUtils.isNotBlank(halfLifePeriod)){
            String[] hlpArray = halfLifePeriod.split(CommonConsts.SPIT);
            wrapper.in("t2.ingr_half_life_period_code", Arrays.asList(hlpArray));
        }
        if(StringUtils.isNotBlank(content)){
            wrapper.and(w->w.like("t2.ingr_zh_name", content)
                    .or().like("t2.ingr_en_name", content)
                    .or().like("t2.ingr_latin_name", content));
        }
        wrapper.in("t1.herb_id", herbList);
        List<EtcmHerbIngrPo> herbIngrPos = etcmPxHerbMapper.getIngr(wrapper);
        List<Map<String,String>> resultList=new ArrayList<>();
        for(EtcmHerbIngrPo etcmHerbIngrPo:herbIngrPos){
            List<EtcmIngrExPo> exList = etcmPxHerbMapper.getIngrDetailslist(new QueryWrapper<EtcmIngrExPo>().eq(EtcmIngrExPo.INGR_ID, etcmHerbIngrPo.getIngrId()).eq(EtcmIngrExPo.STATUS, CommonConsts.STR_COMMON_YES).eq(EtcmIngrExPo.UI_TYPE_CODE, uiTypeCode).eq(EtcmIngrExPo.LANGUAGE_CODE, langCode));
            Map<String,String> map=new HashMap<>(16);
            for(EtcmIngrExPo etcmIngrExPo:exList){
                map.put(etcmIngrExPo.getUiElName(), etcmIngrExPo.getIngrExCon());
            }
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public List<Map<String, String>> getTarget(String targetType, String content, String langCode, String uiTypeCode, String prescriptionId) {
        QueryWrapper<EtcmTargetPo> wrapper=new QueryWrapper<>();
        wrapper.eq("t1.px_id", prescriptionId);
        if(StringUtils.isNotBlank(targetType)){
            String[] targetArray = targetType.split(CommonConsts.SPIT);
            wrapper.in("t4.target_type_code", targetArray);
        }
        if(StringUtils.isNotBlank(content)){
            wrapper.and(w->w.like("t4.target_zh_name", content)
                    .or().like("t4.target_en_name", content)
                    .or().like("t4.target_latin_name", content));
        }

        List<EtcmTargetPo> targetPos = etcmPxHerbMapper.getTarget( wrapper);
        List<Map<String,String>> resultList=new ArrayList<>();
        for(EtcmTargetPo etcmTargetPo:targetPos){
            List<EtcmTargetExPo> exList = etcmPxHerbMapper.getTargetDetails(new QueryWrapper<EtcmTargetExPo>().eq(EtcmTargetExPo.TARGET_ID,etcmTargetPo.getId()).eq(EtcmIngrExPo.STATUS, CommonConsts.STR_COMMON_YES).eq(EtcmTargetExPo.UI_TYPE_CODE, uiTypeCode).eq(EtcmTargetExPo.LANGUAGE_CODE, langCode));
            Map<String,String> map=new HashMap<>(16);
            for(EtcmTargetExPo etcmTargetExPo:exList){
                map.put(etcmTargetExPo.getUiElCode(), etcmTargetExPo.getTargetExCon());
            }
            resultList.add(map);
        }
        return resultList;
    }

    @Override
    public ResultModel<PxHerbStatisticsRespVo> herbStatistics(String prescriptionId, String content, String uiTypeCode, String langCode,String herbMeridians,String herbProperty,String herbFlavor) {
        QueryWrapper<EtcmHerbPo> queryWrapper=new QueryWrapper<>();
        if(StringUtils.isNotBlank(content)){
            queryWrapper.and(w->w.like( "t2.herb_zh_name", content)
                    .or().like( "t2.herb_zh_name_py", content)
                    .or().like( "t2.herb_zh_name_wb", content)
                    .or().like( "t2.herb_zh_name_abb", content)
                    .or().like( "t2.herb_en_name", content)
                    .or().like( "t2.herb_en_name_abb", content)
                    .or().like( "t2.herb_latin_name", content)
                    .or().like( "t2.herb_latin_name_abb", content)
                    .or().like( "t2.herb_name_alias", content)
            );
        }


        if(StringUtils.isNotBlank(herbMeridians)){
            queryWrapper.in("t6.meridians_code",herbMeridians.split(CommonConsts.SPIT));
        }
        if(StringUtils.isNotBlank(herbProperty)){
            queryWrapper.in("t5.property_code",herbProperty.split(CommonConsts.SPIT));
        }
        if(StringUtils.isNotBlank(herbFlavor)){
            queryWrapper.in("t4.flavor_code",herbFlavor.split(CommonConsts.SPIT));
        }


        queryWrapper.groupBy("t1.herb_id");
        List<EtcmHerbPo> list = etcmPxHerbMapper.herbStatistics(queryWrapper, prescriptionId);
        PxHerbStatisticsRespVo vo = new PxHerbStatisticsRespVo();
        Map<String,String> resMap = new LinkedHashMap<>(16);
        Map<String,String> hisMap = new LinkedHashMap<>(16);
        long totalCount = 0;
        for (EtcmHerbPo etcmHerbPo : list) {
            totalCount = totalCount + Long.parseLong(etcmHerbPo.getQuantity());
            if (StringUtils.isBlank(etcmHerbPo.getHerbEnName()) && StringUtils.isBlank(etcmHerbPo.getHerbZhName())){
                continue;
            }
            if (CommonConsts.LANG_CODE_ENG.equals(langCode)){
                hisMap.put(etcmHerbPo.getHerbEnName(),etcmHerbPo.getQuantity());
            }
            if (CommonConsts.LANG_CODE_CHN.equals(langCode)){
                hisMap.put(etcmHerbPo.getHerbZhName(),etcmHerbPo.getQuantity());
            }

        }
        for (EtcmHerbPo etcmHerbPo : list) {
            BigDecimal totalSize = new BigDecimal(totalCount);
            BigDecimal size = new BigDecimal(etcmHerbPo.getQuantity());
            BigDecimal bigDecimal = size.divide(totalSize,2, RoundingMode.HALF_UP).multiply(new BigDecimal(100));
            if (StringUtils.isBlank(etcmHerbPo.getHerbEnName()) && StringUtils.isBlank(etcmHerbPo.getHerbZhName())){
                continue;
            }
            if (CommonConsts.LANG_CODE_ENG.equals(langCode)){
                resMap.put(etcmHerbPo.getHerbEnName(),bigDecimal.toString());

            }
            if (CommonConsts.LANG_CODE_CHN.equals(langCode)){
                resMap.put(etcmHerbPo.getHerbZhName(),bigDecimal.toString());
            }
        }



        vo.setHistogramStatistics(hisMap);
        vo.setPieStatistics(resMap);
        return new ResultModel<PxHerbStatisticsRespVo>().success(vo);
    }


}
